//
//  OfficialLoginController.swift
//  AirTravel
//
//  Created by apple on 2021/8/13.
//

import UIKit
import Moya
import SwiftyJSON

class OfficialLoginController: UIViewController {

    @IBOutlet weak var loginBtn: UIButton!
    @IBOutlet weak var chooseBtn: UIButton!
    @IBOutlet weak var passwordTF: UITextField!
    @IBOutlet weak var accountTF: UITextField!
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        self.navigationController?.navigationBar.tintColor = UIColor.black
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.black]
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.white]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.loginBtn.layer.cornerRadius = 5
        self.loginBtn.layer.masksToBounds = true
    }


    
    @IBAction func choose(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    //协议
    @IBAction func agreement(_ sender: Any) {
    }
    
    @IBAction func login(_ sender: Any) {
        guard let username = self.accountTF.text else {
            YProgressHUD.showToast("账号不能为空")
            return
        }
        guard let password = self.passwordTF.text else {
            YProgressHUD.showToast("密码不能为空")
            return
        }
        if self.chooseBtn.isSelected {
            cancelableRequest = NetWorkRequest(API1.apply12306Login(parameters: ["username":username,"password":password]), completion: {[weak self] (responseString) -> (Void) in
                YProgressHUD.showToast("登录成功")
                UserDefaults.standard.setValue(self?.accountTF.text ?? "", forKey: "12306Login")
                UserDefaults.standard.setValue(self?.passwordTF.text ?? "", forKey: "12306Password")
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self?.navigationController?.popViewController(animated: true)
                }
            }, failed: { (failedResutl) -> (Void) in
                print("服务器返回code不为0000啦~\(failedResutl)")
            }, errorResult: { () -> (Void) in
                print("网络异常")
            })
        }else{
            YProgressHUD.showToast("请阅读并同意《12306账号授权及预定协议》")
        }
    }
    
    
}
